package cn.icanci.loopstack.bic.biz.dts.impl;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.google.common.collect.Sets;

import cn.icanci.loopstack.bic.biz.dts.DTS;
import cn.icanci.loopstack.bic.biz.dts.GraphDtsService;
import cn.icanci.loopstack.bic.biz.service.SnapshotService;
import cn.icanci.loopstack.bic.biz.service.UnitViewService;
import cn.icanci.loopstack.bic.common.model.base.EdgeStyleVO;
import cn.icanci.loopstack.bic.common.model.graph.UnitEdgeVO;
import cn.icanci.loopstack.bic.common.model.graph.UnitViewVO;

/**
 * @author icanci
 * @since 1.0 Created in 2023/09/20 20:05
 */

@Service
@DTS(EdgeStyleVO.class)
public class EdgeStyleDtsServiceImpl implements GraphDtsService<EdgeStyleVO> {
    @Resource
    private SnapshotService snapshotService;
    @Resource
    private UnitViewService unitViewService;

    @Override
    public void dtsUnitViewTree(EdgeStyleVO edgeStyle) {
        List<UnitViewVO> unitViews = unitViewService.queryBySystemUuid(edgeStyle.getSystemUuid());
        if (CollectionUtils.isEmpty(unitViews)) {
            return;
        }

        Set<String> useCaseUuids = Sets.newHashSet();
        for (UnitViewVO unitView : unitViews) {
            List<UnitEdgeVO> edges = unitView.getEdges();
            if (CollectionUtils.isEmpty(edges)) {
                continue;
            }

            for (UnitEdgeVO edge : edges) {
                if (StringUtils.equals(edgeStyle.getUuid(), edge.getStyleUuid())) {
                    useCaseUuids.add(unitView.getUseCaseUuid());
                }
            }
        }
        // TODO 如果执行的慢可以使用线程池进行更新，此处暂不处理
        useCaseUuids.forEach(useCaseUuid -> {
            snapshotService.refresh(edgeStyle.getSystemUuid(), useCaseUuid);
        });
    }
}
